import level_PeopleArcheryUnitBase from "../base/level_PeopleArcheryUnitBase";
import { peopleArcheryUnitTag } from "../const/peopleArcheryConst";
import level_peopleArcheryOption from "./level_peopleArcheryOption";
import level_PeopleArcheryBullet from "./level_peopleArcheryBullet";
import level_peopleArcheryEnemy from "./level_peopleArcheryEnemy";
import O1HD from "../../../engines/gameEngine";
import { CsvFileKind } from "../../../engines/libs/CsvFileKind";
import level_peopleArchery from "../level_peopleArchery";
import mainRoot from "../../../Game/MainRoot";

const {ccclass, property} = cc._decorator;

@ccclass
export default class level_peopleArcheryPeople extends level_PeopleArcheryUnitBase {

    @property({type:cc.Node,tooltip:"普通角色形象节点"})
    /**  角色形象节点 */
    peopleNode_normal:cc.Node = null;

    // @property({type:cc.Node,tooltip:"魔角色形象节点"})
    // /**  角色形象节点 */
    // peopleNode_mo:cc.Node = null;

    // @property({type:cc.Node,tooltip:"仙角色形象节点"})
    // /**  角色形象节点 */
    // peopleNode_xian:cc.Node = null;

    @property({type:cc.Node,tooltip:"普通云节点"})
    /**  角色形象节点 */
    cloud_normal:cc.Node = null;

    @property({type:cc.Node,tooltip:"魔云节点"})
    /**  角色形象节点 */
    cloud_mo:cc.Node = null;

    @property({type:cc.Node,tooltip:"仙云节点"})
    /**  角色形象节点 */
    cloud_xian:cc.Node = null;

    @property({type:cc.Label,tooltip:"text文本"})
    lbText:cc.Label = null;

    @property({type:cc.Node,tooltip:"受伤图片"})
    hurtNode:cc.Node = null;

    @property({type:cc.Node,tooltip:"刀光特效"})
    cutEffect:cc.Node = null;

    @property({type:cc.Node,tooltip:"回血动画节点"})
    addHpNode:cc.Node = null;

    @property({type:cc.Node,tooltip:"仙角色形象装饰"})
    xianDecorate:cc.Node[] = [];

    @property({type:cc.Node,tooltip:"魔角色形象装饰"})
    moDecorate:cc.Node[] = [];

    @property({type:cc.Node,tooltip:"雷节点"})
    rayNode:cc.Node = null;

    @property({type:cc.Node,tooltip:"称号节点"})
    titleNode:cc.Node = null;

    @property({type:cc.SpriteFrame,tooltip:"标题图片"})
    titleSp:cc.SpriteFrame[] = [];

    peopleNode:cc.Node = null;

    cloudNode:cc.Node = null;

    /**当前形象 */
    profile:string = "0";

    /**箭的移动距离 */
    private _arrowDis:number = 0;
    /**箭的最小移动距离 */
    private _minArrowDis:number = 0;
    /**箭的最大移动距离 */
    private _maxArrowDis:number = 0;

    /**获取最小攻击距离 */
    get minArrowDis():number {return this._minArrowDis;}
    /**设置最小攻击距离 */
    set minArrowDis(value:number) {this._minArrowDis = value;}

    /**获取最大攻击距离 */
    get maxArrowDis():number {return this._maxArrowDis;}
    /**设置最大攻击距离 */
    set maxArrowDis(value:number) {this._maxArrowDis = value;}

    /**获取箭的距离 */
    get arrowDis():number {return this._arrowDis;}
    /**设置箭的距离 */
    set arrowDis(value:number) {
        this._arrowDis = Math.max(this._minArrowDis,value);
        this._arrowDis = Math.min(this._maxArrowDis,value);
    }

    /**子弹数量 */
    private _bulletNum:number = 1;

    get bulletNum():number {return this._bulletNum;}
    set bulletNum(value:number) {this._bulletNum = value;}
    
    get initAtk(){
        return this._atkSpd;
    }

    /**获取攻速 */
    get atkSpd() {
        let atkSpd = this._atkSpd + this.atkSpdAdd;
        atkSpd = Math.max(atkSpd,this.minAtkSpd);
        atkSpd = Math.min(atkSpd,this.maxAtkSpd);
        return atkSpd;
    }
    /**设置攻速 */
    set atkSpd(atkSpd: number) {
        this._atkSpd = Math.max(atkSpd,this._minAtkSpd);
        this._atkSpd = Math.min(atkSpd,this._maxAtkSpd);
    }

    //每行最大的箭的数量
    private maxRowLength:number = 10;

    //每只箭X的间隔
    private arrowXInterval:number = 50;

    synthesisFlag:boolean = false;

    lastShotTime:number = 0;

    curRoleTime:number = 0;

    xianTitle:string[] = ["羽化成仙","天界上仙","大罗金仙"];
    moTitle:string[] = ["弃世入魔","炼狱魔王","修罗无双"];
    bossTitle:string[] = ["小试牛刀","初露锋芒","炉火纯青","孤独求败","飞升大乘"];

    xianMoIndex:number = 0;
    bossIndex:number = 0;


    bindLevel(level: level_peopleArchery): void {
        super.bindLevel(level);
        let roleData = level.roleData;
        let rPath = roleData["role_path"];
        mainRoot.frameBundle.load(`Img/Game/common/peopleArcheryRole/${rPath}`,cc.SpriteFrame,(err,spf:cc.SpriteFrame)=>{
            if(err){
                console.log("加载角色图片失败");
                return;
            }
            this.peopleNode_normal.getComponent(cc.Sprite).spriteFrame = spf;
        });
    }

    start(){
        this.changeProfile("0");
        this.cutEffect.width = 0;
        this.cutEffect.active = false;
        this.xianDecorate.forEach((n:cc.Node)=>{
            n.active = false;
        });
        this.moDecorate.forEach((n:cc.Node)=>{
            n.active = false;
        });
        this.rayNode.active = false;
    }

    shotBullet(){
        let bulletNum = this.bulletNum;
        let posAry:number[] = this.getArrowPos(bulletNum);
        this.peopleNode.getComponent(cc.Animation).play();
        // O1HD.getManagers().soundMgr.playSound("peopleArcherySound/Shoot");
        for(let i = 0;i<this.bulletNum;i++){
            let bullet = this.level.getOneBullet();
            cc.Tween.stopAllByTarget(bullet);
            let bs = bullet.getComponent(level_PeopleArcheryBullet);
            bs.moveSpd =  Number(this.level.peopleArcheryData["arrowMoveSpd"]);
            bs.atk = this.shotAtk;
            bs.shotLeech = this.shotLeech;
            bs.criticalPro = this.criticalPro;
            bs.criticalAddition = this.criticalAddition;
            bs.setMaxDis(this.arrowDis);
            bs.initBullet();
            let posX = this.node.x + posAry[i];
            let tX:number = this.node.x;
            this.level.oneUnitBindLevel(bs);
            bullet.setPosition(tX,this.node.y +230);
            bullet.setParent(this.level.unitContent);
            cc.tween(bullet).to(0.2,{x:posX}).start();
        }
    }

    shot(){
        if(this.curRoleTime - this.lastShotTime >= 1 / this.atkSpd){
            this.lastShotTime = this.curRoleTime;
            this.shotBullet();
        }
    }

    onCollisionEnter(other: cc.Collider, self: cc.Collider): void {
        switch(other.tag){
            case peopleArcheryUnitTag.enemy:{
                // 碰到了敌方
                let os = other.node.getComponent(level_peopleArcheryEnemy);
                let hp = os.hp;
                os.unitDeath();
                this.unitBeHurt(hp,"1");
                os.redSharkAni();
                if(this.profile == "2"){
                    this.cutAni();
                }
                break;
            }
            case peopleArcheryUnitTag.option:{
                // 碰到了选项
                let os = other.node.getComponent(level_peopleArcheryOption);
                os.clearGroupOption();
                let oProfile = os.optionType;
                if(this.profile == "0" && oProfile != "0"){
                    this.changeProfile(oProfile);
                } 
                let oData = os.data;
                if(!oData){
                    return;
                }
                let waveData = os.wavaData;
                let oType = waveData.option_Type;
                switch(oType){
                    case "1":{
                        if(this.profile == "1"){
                            this.showTitle("0");
                        }else{
                            this.showTitle("1");
                        }
                        this.level.parseDataAddPeople(oData);
                        break;
                    }
                    case "2":
                    case "3":
                    case "4":
                    case "5":{
                        let d = os.surviveCatastropheData;
                        let successProAry:number[] = d.surviveCatastrophe_option_pro.split("|").map((v)=>{
                            return Number(v);
                        });
                        let successPro:number = successProAry[os.groupIndex];
                        if(Math.random() < successPro){
                            this.level.parseDataAddPeople(oData);
                            this.showTitle("4");
                        }else{
                            this.rayAni();
                            this.showTitle("5");
                        }
                        break;
                    }
                    default:{
                            this.level.parseDataAddPeople(oData);
                        break;
                    }
                }
                this.level.curWave ++;
                os.unitDeath();
                break;
            }
        }
    }

    update(dt: number){
        //如果游戏已经暂停则直接return
        this.refrenshText();
        if(this.level.gamePauseFlag){
            return;
        }
        super.update(dt);
        this.curRoleTime += dt;
        this.shot();
    }

    refrenshText(){
        // this.lbText.string = `血量\n${this.hp}\n攻速\n${this.atkSpd}\n攻击力\n${this.atk}\n永久攻击\n${O1HD.getManagers().peopleArcheryManager.getData().atkAddition}`;
        this.lbText.string = `${this.hp}`;
    }

    /**
     * 获取箭的位置
     * @param length 箭的数量
     * @returns 箭的位置
     */
    getArrowPos(length:number){
        let posAry:number[] = [];
        let rowCount:number = 0;
        rowCount = length; //(length % this.maxRowLength == 0) ? this.maxRowLength : length % this.maxRowLength;
        let interval = rowCount % 2 == 0 ? this.arrowXInterval / 2 : 0;
        let halfLength:number = Math.floor(rowCount / 2);
        if(rowCount % 2 != 0){
            posAry.push(0);
        }
        for(let j = 0; j < halfLength; j++){
            let index = j + 1;
            let oneVecX = index * this.arrowXInterval - interval;
            let twoVecX = -index * this.arrowXInterval + interval;
            posAry.push(oneVecX);
            posAry.unshift(twoVecX);
        }
        return posAry;
    }

    async unitDeath(){
        // this.level.gameFail();
        // if(this.lastWaveFlag){
        // 打开获得修为界面
        this.level.openMoneyPage(false);
        super.unitDeath();
    }

    unitDestroy(){
        this.peopleNode.active = false;
    }

    alive(){
        this.isDeath = false;
        this.node.getComponent(cc.Collider).enabled = true;
        this.peopleNode.active = true;
        this.node.opacity = 255;

        this.level.parseDataAddPeople({param_type:"0",option_param:"1000"})

        // this.hp = Math.min(Number(this.level.peopleArcheryData["initHp"]),this.maxHp);
    }

    async unitBeHurtAni(){
        return;
        cc.Tween.stopAllByTarget(this.node);
        this.hurtNode.active = true;
        cc.tween(this.node).delay(0.2).call(()=>{
            this.hurtNode.active = false;
        }).start();
    }

    /**
     * 更改角色皮肤
     * @param skinId 皮肤id
     */
    changeRoleSkin(skinId:string){
        if(this.peopleNode){
            this.peopleNode.active = false;
        }
        if(this.cloudNode){
            this.cloudNode.active = false;
        }
        switch(skinId){
            case "0":{
                    this.peopleNode = this.peopleNode_normal;
                    this.cloudNode = this.cloud_normal;
                break;
            }
            case "1":{
                // this.peopleNode = this.peopleNode_xian;
                this.cloudNode = this.cloud_xian;
                break;
            }
            case "2":{
                // this.peopleNode = this.peopleNode_mo;
                this.cloudNode = this.cloud_mo;
                break;
            }
        }
        this.peopleNode.active = true;
        this.cloudNode.active = true;
    }
    
    /**
     * 更改角色类型
     * @param profileType 0 普通 1仙 2魔
     */
    changeProfile(profileType:string){
        this.profile = profileType;
        this.changeRoleSkin(profileType);
        switch(profileType){
            case "0":{
                this.xianDecorate.forEach((n:cc.Node)=>{
                    n.active = false;
                });
                this.moDecorate.forEach((n:cc.Node)=>{
                    n.active = false;
                });
                break;
            }
            case "1":{
                this.xianDecorate.forEach((n:cc.Node)=>{
                    n.active = true;
                });
                break;
            }
            case "2":{
                this.moDecorate.forEach((n:cc.Node)=>{
                    n.active = true;
                });
                break;
            }
        }
    }

    cutAni(){
        cc.Tween.stopAllByTarget(this.cutEffect);
        this.cutEffect.active = true;
        this.cutEffect.width = 0;
        this.cutEffect.opacity = 255;
        cc.tween(this.cutEffect).to(0.1, {width: 320}).to(0.1,{opacity:0}).start();
    }

    addHpAni(){
        this.addHpNode.active = true;
        let ani = this.addHpNode.getComponent(cc.Animation);
        ani.play();
        ani.on('finished',this.onAddHpFinished,this);
    }

    onAddHpFinished(){
        this.addHpNode.active = false;
    }

    addOneWeapon(weaponId: string): void {
        super.addOneWeapon(weaponId);
        let data = O1HD.getManagers().csvDataManager.getCsvDataItem(CsvFileKind.CsvFile.peopleArcheryMagicWeapon,weaponId);
        let can_synthesis_id = data["can_synthesis_id"];
        let synthesisId = data["synthesis_id"];
        if(can_synthesis_id && synthesisId && !this.synthesisFlag){
            if(this._weapons.includes(can_synthesis_id)){
                this.level.roleAddWeapon(synthesisId);
                this.synthesisFlag = true;
                this.level.openSynthPage(synthesisId,can_synthesis_id,weaponId);
            }
        }
    }

    getWeapons(){
        return this._weapons;
    }

    /**雷劈动画 */
    rayAni(){
        this.rayNode.active = true;
        let ani:cc.Animation = this.rayNode.getComponent(cc.Animation);
        ani.play("animation");
        ani.on("finished",()=>{
            this.peopleNode_normal.color = cc.color(50,50,50);
            cc.tween(this.peopleNode_normal).delay(1).call(()=>{
                this.peopleNode_normal.color = cc.color(255,255,255);
            }).start();
            this.rayNode.active = false;
        });
    }

    /**
     * 展示称号
     * @param titleType 称号类型 0：仙 1：魔 2：boss 3：法宝 4 渡劫成功 5渡劫失败
     * */
    showTitle(titleType:string){
        let spf:cc.SpriteFrame = null;
        let titleNode:cc.Node = cc.instantiate(this.titleNode);
        let sp:cc.Sprite = titleNode.getComponent(cc.Sprite);
        let lb:cc.Label = titleNode.getChildByName("lbTitle").getComponent(cc.Label);
        let chat:string = "";
        switch(titleType){
            case "0":{
                spf = this.titleSp[0];
                if(this.xianMoIndex >= this.xianTitle.length){
                    this.xianMoIndex = this.xianTitle.length - 1;
                }
                chat = this.xianTitle[this.xianMoIndex];
                this.xianMoIndex ++;
                break;
            }
            case "1":{
                spf = this.titleSp[1];
                if(this.xianMoIndex >= this.moTitle.length){
                    this.xianMoIndex = this.moTitle.length - 1;
                }
                chat = this.moTitle[this.xianMoIndex];
                this.xianMoIndex ++;
                break;
            }
            case "2":{
                spf = this.titleSp[0];
                if(this.bossIndex >= this.bossTitle.length){
                    this.bossIndex = this.bossTitle.length - 1;
                }
                chat = this.bossTitle[this.bossIndex];
                this.bossIndex ++;
                break;
            }
            case "3":{
                spf = this.titleSp[0];
                break;
            }
            case "4":{
                if(this.profile == "1"){
                    spf = this.titleSp[0];
                }else{
                    spf = this.titleSp[1];
                }
                chat = "渡劫成功";
                O1HD.getManagers().soundMgr.playSound("peopleArcherySound/Door");
                break;
            }
            case "5":{
                spf = this.titleSp[2];
                chat = "渡劫失败";
                O1HD.getManagers().soundMgr.playSound("peopleArcherySound/RedDoor");
                break;
            }
        }
        sp.spriteFrame = spf;
        lb.string = chat;
        titleNode.setParent(this.node);
        titleNode.active = true;
        titleNode.zIndex = 1000;
        titleNode.scale = 0;
        cc.tween(titleNode).to(0.2,{scale:1},{easing:cc.easing.backOut}).delay(2).to(0.5,{opacity:0}).call(()=>{
            titleNode.destroy();
            titleNode.removeFromParent();
        }).start();
    }

}
